package cn.lingyangwl.agile.msg.push.controller;

import cn.lingyangwl.agile.model.module.tenant.*;
import cn.lingyangwl.agile.msg.push.core.propcess.*;
import cn.lingyangwl.agile.msg.push.model.rqrs.history.*;
import cn.lingyangwl.agile.msg.push.service.*;
import cn.lingyangwl.agile.ram.*;
import cn.lingyangwl.agile.tenant.core.utils.*;
import cn.lingyangwl.framework.core.response.*;
import cn.lingyangwl.framework.security.ratelimit.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author shenguangyang
 */
@Api(tags = "消息推送")
@RestController
@RequestMapping("/msgHistory")
public class MsgHistoryController {

    @Resource
    private MsgPushProcess msgPushHandler;

    @Resource
    private MsgHistoryService msgHistoryService;

    /**
     * 分页 消息推送
     */
    @RamResource(action = "msg:history:list", name = "查询消息推送记录列表", type = ActionType.READ)
    @GetMapping("/page")
    public Resp<IPage<HistoryQueryResp>> pageHistory(@Validated HistoryPageReq req) {
        if (Boolean.TRUE.equals(req.getIsQueryAllTenant()) && TenantContext.get().isMainTenant()) {
            return TenantUtils.executeIgnore(() -> Resp.ok(msgHistoryService.pageHistory(req)));
        }
        return Resp.ok(msgHistoryService.pageHistory(req));
    }

    /**
     * 通过id查找 消息推送
     */
    @RamResource(action = "msg:history:get", name = "查询消息推送记录", type = ActionType.READ)
    @GetMapping("/get")
    public Resp<HistoryQueryResp> getById(@RequestParam(value = "id") Long id) {
        return Resp.ok(msgHistoryService.getById(id));
    }

    /**
     * 重新推送消息, 需要做防刷操作
     * @param id 消息id
     */
    @PostMapping("/rePush")
    @RamResource(action = "msg:history:rePush", name = "重新推送消息", type = ActionType.WRITE)
    @RateLimit(limitType = LimitTypeEnum.IP, time = 10, count = 2)
    public Resp<?> rePush(@RequestParam(value = "id") Long id) throws Exception {
        msgHistoryService.rePush(id);
        return Resp.ok();
    }

    /**
     * 批量删除 消息推送
     */
    @RamResource(action = "msg:history:delete", name = "删除消息推送记录", type = ActionType.WRITE)
    @DeleteMapping("/batchDelete")
    public Resp<?> deleteBatch(@RequestParam(value = "ids") List<Long> ids) {
        return Resp.ok(msgHistoryService.deleteByIds(ids));
    }

    /**
     * 删除 消息推送
     */
    @RamResource(action = "msg:history:delete", name = "删除消息推送记录", type = ActionType.WRITE)
    @DeleteMapping("/delete")
    public Resp<?> delete(@RequestParam(value = "id") Long id) {
        return Resp.ok(msgHistoryService.deleteById(id));
    }
}
